/*
 * @Author: yuelin.ye
 * @Date: 2021-06-29 09:05:23
 * @LastEditors: yuelin.ye
 * @LastEditTime: 2021-06-29 10:47:40
 * @Description:
 */
const parser = require('@babel/parser')
const compiler = require('vue-template-compiler')
const loaderUtils = require('loader-utils')
const total = {
  len: 0,
  components: {}
}
const sortable = (obj) => Object.fromEntries(Object.entries(obj).sort(([, a], [, b]) => b - a))
module.exports = function (source) {
  debugger
  const options = loaderUtils.getOptions(this)
  console.log('options', options)
  try {
    //  Single-File Components(SFC) => script
    const component = compiler.parseComponent(source)
    // script => AST
    const ast = parser.parse(component.script.content, {
      sourceType: 'module',
      plugins: ['js']
    })
    // console.log('ast', ast)
    if (ast) {
      // setTimeout(() => {
      const getImport = 'ImportDeclaration'
      const importAst = ast.program.body.filter(
        // type 节点类型，这里我们去过滤 import 声明类型 同时去过滤
        (i) => i.type === getImport
      )

      total.len = total.len + importAst.length

      for (let i of importAst) {
        const { specifiers = [] } = i
        for (let s of specifiers) {
          if (s.local) {
            const { name } = s.local
            total.components[name] = total.components[name] ? total.components[name] + 1 : 1
          }
        }
      }
      total.components = sortable(total.components)
      // console.log(total, 'total')
      this.callback(null, source)
      // }, 0)
    } else { this.callback(null, source) }
  } catch (error) {
    console.error(error)
    this.callback(null, source)
  }
}
